import { api_list } from './config'

export async function Http(method, {url, data, header = {}, ...customConfig}) {
  let token = wx.getStorageSync('token');
  
  if(token){
    header['Authorization'] = token
  }

  let option = {
    url: api_list[url || ''],
    method,
    header: Object.assign({
      'Content-Type': 'application/json;chatset=utf-8'
    }, header),
    data,
    timeout: 20000,
    ...customConfig
  }

  return new Promise((resolve, reject) => {
    wx.request({
      ...option,
      success: (result) => {
        if(result.data.state) {
          resolve(result.data);
        }else{
          resolve({
            error: result.data.code,
            errMsg: result.data.errMsg
          })
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
  
}

export function useHttp(method, config){
	return Http(method, {...config});
}

export function _post(setting){
	setting.method = 'POST';
	return Http(setting);
}

export function _all(setting){
	let pro = setting.map(item => {
		return _post(item);
	});

	return Promise.all(pro);
}